using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Net;

using DirkRettschlag.Utils;
using System.Text.RegularExpressions;
using System.Collections;

namespace Departure
{
    public partial class frmStationSettings : Form
    {

        private HttpWebRequest request;
        private StationSettings stationSettings;
        private GeneralSettings generalSettings;
        
        string transfers;
        string transfersSelected = "000000000000";

        SortedList<string, string> stations;
        string stationID = "";

        Departure.Webservice.WebserviceWrapper ws = new Departure.Webservice.WebserviceWrapper();
        
        public StationSettings StationSettings
        {
            get
            {
                return this.stationSettings;
            }
            set
            {
                this.stationSettings = value;
                this.stationSettings.getSettings();
                this.setControls();
            }
        }

        public GeneralSettings GeneralSettings
        {
            set { this.generalSettings = value; }
        }

        public frmStationSettings()
        {
            InitializeComponent();

            this.tbcSettings.Top = 0;
            this.tbcSettings.Left = 0;
            this.tbcSettings.Height = this.ClientSize.Height;
            this.tbcSettings.Width = this.ClientSize.Width;
        }

        private void setControls()
        {
            txtStation.Text = this.stationSettings.Station;
            txtAbbreviation.Text = this.stationSettings.Abbreviation;

            string tmpTransfers = this.stationSettings.TransfersSelected;

            if (tmpTransfers[0].ToString() == "1") { chkICE.Checked = true; } else { chkICE.Checked = false; }
            if (tmpTransfers[1].ToString() == "1") { chkECIC.Checked = true; } else { chkECIC.Checked = false; }
            if (tmpTransfers[2].ToString() == "1") { chkIR.Checked = true; } else { chkIR.Checked = false; }
            if (tmpTransfers[3].ToString() == "1") { chkIRE.Checked = true; } else { chkIRE.Checked = false; }
            if (tmpTransfers[4].ToString() == "1") { chkRE.Checked = true; } else { chkRE.Checked = false; }
            if (tmpTransfers[5].ToString() == "1") { chkRB.Checked = true; } else { chkRB.Checked = false; }
            if (tmpTransfers[6].ToString() == "1") { chkSBahn.Checked = true; } else { chkSBahn.Checked = false; }
            if (tmpTransfers[7].ToString() == "1") { chkBus.Checked = true; } else { chkBus.Checked = false; }
            if (tmpTransfers[8].ToString() == "1") { chkBoat.Checked = true; } else { chkBoat.Checked = false; }
            if (tmpTransfers[9].ToString() == "1") { chkUBahn.Checked = true; } else { chkUBahn.Checked = false; }
            if (tmpTransfers[10].ToString() == "1") { chkTram.Checked = true; } else { chkTram.Checked = false; }
            if (tmpTransfers[11].ToString() == "1") { chkTaxi.Checked = true; } else { chkTaxi.Checked = false; }

            chkTrainsFilter.Checked = this.stationSettings.UseTrainsFilter;
            txtTrainsFilter.Text = this.stationSettings.TrainsFilter;

            chkDirectionsFilter.Checked = this.stationSettings.UseDirectionsFilter;
            txtDirectionsFilter.Text = this.stationSettings.DirectionsFilter;

            chkPlatformsFilter.Checked = this.stationSettings.UsePlatformsFilter;
            txtPlatformsFilter.Text = this.stationSettings.PlatformsFilter;

            rbtFilterLogicAND.Checked = this.stationSettings.UseAndFilter;
            rbtFilterLogicOR.Checked = !rbtFilterLogicAND.Checked;
        }

        private void setStationSettings()
        {
            this.stationSettings.Station = txtStation.Text;
            this.stationSettings.StationID = this.stationID;
            this.stationSettings.Abbreviation = txtAbbreviation.Text;
            this.stationSettings.Transfers = transfers;
            this.stationSettings.TransfersSelected = transfersSelected;
            this.stationSettings.UseTrainsFilter = chkTrainsFilter.Checked;
            this.stationSettings.TrainsFilter = txtTrainsFilter.Text;
            this.stationSettings.UseDirectionsFilter = chkDirectionsFilter.Checked;
            this.stationSettings.DirectionsFilter = txtDirectionsFilter.Text;
            this.stationSettings.UsePlatformsFilter = chkPlatformsFilter.Checked;
            this.stationSettings.PlatformsFilter = txtPlatformsFilter.Text;
            this.stationSettings.UseAndFilter = rbtFilterLogicAND.Checked;
        }

        private void mniSave_Click(object sender, EventArgs e)
        {
            this.setStationSettings();
            this.stationSettings.saveSettings();

            this.cboChoose.Visible = false;
            this.lblChoose.Text = "";

            this.Close();
        }

        private void mniCancel_Click(object sender, EventArgs e)
        {
            this.stationSettings.getSettings();
            this.setControls();

            this.cboChoose.Visible = false;
            this.lblChoose.Text = "";

            this.Close();
        }

        private void inputPanel_EnabledChanged(object sender, EventArgs e)
        {
            if (this.inputPanel.Enabled)
            {
                this.tbcSettings.Height -= this.inputPanel.Bounds.Height;
            }
            else
            {
                this.tbcSettings.Height = this.ClientSize.Height;
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {

                if (Utilities.Connected() || generalSettings.AutoConnect)
                {

                    Cursor.Current = Cursors.WaitCursor;


                    this.lblChoose.Text = "Searching...";
                    this.lblChoose.Refresh();
                    this.cboChoose.Items.Clear();

                    Application.DoEvents();

                    if (generalSettings.UseWebService)
                    {
                        ws.setURL(generalSettings.WebServiceURL);
                        ws.BeginFindStation(generalSettings.DeviceID, this.txtStation.Text, new AsyncCallback(FindStationCallback), ws);
                    }
                    else
                    {
                        request = (HttpWebRequest)WebRequest.Create("http://reiseauskunft.bahn.de/bin/bhftafel.exe/en?L=ua_pda&input=" + this.txtStation.Text + "&time=actual&boardType=dep&productsFilter=0000001000000000&start=Anzeigen&distance=1");

                        request.Credentials = CredentialCache.DefaultCredentials;
                        request.KeepAlive = true;
                        request.Method = "GET";

                        if (generalSettings.UserAgent != "")
                            request.UserAgent = generalSettings.UserAgent;

                        if (generalSettings.HTTPHeader != "")
                            request.Headers.Add(generalSettings.HTTPHeader);

                        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                        System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());

                        string source = sr.ReadToEnd();

                        sr.Close();

                        if (source.IndexOf("Your input is ambiguous.") >= 0)
                        {
                            Regex regex = new Regex("<select name=\"input\".*?</select>", RegexOptions.Singleline | RegexOptions.IgnoreCase);
                            Match match;
                            MatchCollection matchcollection;

                            stations = new SortedList<string, string>();

                            match = regex.Match(source);

                            if (match.Success)
                            {

                                regex = new Regex("<option.*?>.*?</option>", RegexOptions.IgnoreCase);

                                matchcollection = regex.Matches(match.Value);
                                string station;
                                
                                foreach (Match tmpmatch in matchcollection)
                                {
                                    station = Regex.Replace(Utilities.ClearText(tmpmatch.Value), "<option value=\"", "");
                                    station = Regex.Replace(station, "\".*", "");
                                    stations.Add(station.Split('#')[1], station.Split('#')[0]);
                                    this.cboChoose.Items.Add(station.Split('#')[0]);
                                }

                                this.lblChoose.Text = "Multiple Stations found:";

                                this.cboChoose.SelectedIndex = 0;
                                this.cboChoose.Visible = true;

                            }
                            else
                            {
                                this.lblChoose.Text = "Error.";
                            }

                        }
                        else
                        {

                            this.lblChoose.Text = "Station found.";
                        }

                        Cursor.Current = Cursors.Default;
                    }
                }

            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;

                MessageBox.Show(ex.Message, "An error occured");

            }

        }

        private void FindStationCallback(IAsyncResult asyncResult)
        {
            try
            {

                ws = (Webservice.WebserviceWrapper)asyncResult.AsyncState;

                List<string> stations = ws.EndFindStation(asyncResult);

                this.stations = new SortedList<string, string>();

                if (stations.Count > 1)
                {
                    string tmpStation;

                    foreach (string station in stations)
                    {
                        tmpStation = Utilities.ClearText(station);
                        this.stations.Add(tmpStation.Split('#')[1], tmpStation.Split('#')[0]);
                        Invoking.AddComboBoxItem(this.cboChoose, tmpStation.Split('#')[0]);
                    }

                    Invoking.SetText(this.lblChoose, "Multiple Stations found:");

                    Invoking.SetSelectedIndex(this.cboChoose, 0);
                    Invoking.SetControlVisible(this.cboChoose, true);
                }
                else if (stations.Count == 1)
                {
                    Invoking.SetText(this.lblChoose, "Station found.");
                }
                else
                {
                    Invoking.SetText(this.lblChoose, "Error.");
                }

            }
            catch (Exception ex)
            {
                Invoking.SetCursor(this, Cursors.Default);

                MessageBox.Show(ex.Message, "An error occured");

            }

            Invoking.SetCursor(this, Cursors.Default);

        }

        private void cboChoose_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.txtStation.Text = this.cboChoose.SelectedItem.ToString();
            this.stationID = stations.Keys[stations.IndexOfValue(this.cboChoose.SelectedItem.ToString())];
        }

        private void TransportsCheckStateChanged(object sender, EventArgs e)
        {
            transfers = "";

            if (chkICE.Checked) transfers += 1; else transfers += 0;
            if (chkECIC.Checked) transfers += 1; else transfers += 0;
            if (chkIR.Checked) transfers += 1; else transfers += 0;
            if (chkIRE.Checked || chkRE.Checked || chkRB.Checked) transfers += 1; else transfers += 0;
            if (chkSBahn.Checked) transfers += 1; else transfers += 0;
            if (chkBus.Checked) transfers += 1; else transfers += 1; // always use Bus
            if (chkBoat.Checked) transfers += 1; else transfers += 0;
            if (chkUBahn.Checked) transfers += 1; else transfers += 0;
            if (chkTram.Checked) transfers += 1; else transfers += 0;
            if (chkTaxi.Checked) transfers += 1; else transfers += 0;

            transfers += "000000";

            transfersSelected = "";

            if (chkICE.Checked) transfersSelected += 1; else transfersSelected += 0;
            if (chkECIC.Checked) transfersSelected += 1; else transfersSelected += 0;
            if (chkIR.Checked) transfersSelected += 1; else transfersSelected += 0;
            if (chkIRE.Checked) transfersSelected += 1; else transfersSelected += 0;
            if (chkRE.Checked) transfersSelected += 1; else transfersSelected += 0;
            if (chkRB.Checked) transfersSelected += 1; else transfersSelected += 0;
            if (chkSBahn.Checked) transfersSelected += 1; else transfersSelected += 0;
            if (chkBus.Checked) transfersSelected += 1; else transfersSelected += 0;
            if (chkBoat.Checked) transfersSelected += 1; else transfersSelected += 0;
            if (chkUBahn.Checked) transfersSelected += 1; else transfersSelected += 0;
            if (chkTram.Checked) transfersSelected += 1; else transfersSelected += 0;
            if (chkTaxi.Checked) transfersSelected += 1; else transfersSelected += 0;

        }
    }
}
